package org.example;

import instrument.MD5Util;
import product.Movie;
import product.SaleRecord;
import product.Show;
import instrument.FileUtil;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

public class ManagerService {
    private List<Movie> movies = new ArrayList<>();
    private List<Show> shows = new ArrayList<>();
    private List<SaleRecord> saleRecords = new ArrayList<>();
    private User currentManager;
    private Scanner scanner = new Scanner(System.in);
    private AdminService adminService;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    private int showIdCounter = 1000; // 场次ID计数器
    private static final String MOVIE_FILE_PATH = "movies.txt";
    private static final String SHOW_FILE_PATH = "shows.txt";
    private static final String SALE_RECORD_FILE_PATH = "saleRecords.txt";

    public ManagerService(AdminService adminService) {
        this.adminService = adminService;
        // 从文件加载数据（优先于测试数据）
        loadData();
        if (movies.isEmpty() && shows.isEmpty()) {
            initTestData(); // 仅在无数据时初始化测试数据
        }
    }

    // 从文件加载数据
    private void loadData() {
        movies = FileUtil.loadMovies(MOVIE_FILE_PATH);
        shows = FileUtil.loadShows(SHOW_FILE_PATH, movies);
        // 补充销售记录加载逻辑（假设FileUtil有对应方法）
        saleRecords = FileUtil.loadSaleRecords(SALE_RECORD_FILE_PATH, shows);

        // 初始化场次ID计数器
        if (!shows.isEmpty()) {
            showIdCounter = shows.stream()
                    .mapToInt(Show::getId)
                    .max()
                    .getAsInt();
        }
    }

    // 保存数据到文件
    public void saveData() {
        FileUtil.saveMovies(movies, MOVIE_FILE_PATH);
        FileUtil.saveShows(shows, SHOW_FILE_PATH);
        FileUtil.saveSaleRecords(saleRecords, SALE_RECORD_FILE_PATH);
    }

    private void initTestData() {
        // 初始化测试影片
        movies.add(new Movie("流浪地球", "郭帆", "吴京,屈楚萧", "太阳即将毁灭，人类开启流浪地球计划", 125, 9.0, true));
        movies.add(new Movie("满江红", "张艺谋", "沈腾,易烊千玺", "南宋年间的悬疑故事", 159, 8.5, true));

        // 初始化测试场次
        try {
            Date showTime = sdf.parse("2024-05-20 19:30");
            shows.add(new Show(++showIdCounter, movies.get(0), "1号厅", showTime, 50.0, 6, 12));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    // 添加影片
    private void addMovie() {
        System.out.println("\n=== 添加新影片 ===");

        System.out.print("请输入片名：");
        String name = scanner.nextLine().trim();

        // 检查片名是否已存在
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                System.out.println("错误：该影片已存在");
                return;
            }
        }

        System.out.print("请输入导演：");
        String director = scanner.nextLine().trim();

        System.out.print("请输入主演（用逗号分隔）：");
        String actors = scanner.nextLine().trim();

        System.out.print("请输入剧情简介：");
        String intro = scanner.nextLine().trim();

        int duration = 0;
        while (true) {
            System.out.print("请输入时长（分钟）：");
            try {
                duration = Integer.parseInt(scanner.nextLine().trim());
                if (duration > 0) break;
                System.out.println("时长必须为正数");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }

        double score = 0;
        while (true) {
            System.out.print("请输入评分（0-10分）：");
            try {
                score = Double.parseDouble(scanner.nextLine().trim());
                if (score >= 0 && score <= 10) break;
                System.out.println("评分必须在0-10之间");
            } catch (NumberFormatException e) {
                System.out.println("请输入有效数字");
            }
        }

        // 创建并添加影片
        Movie newMovie = new Movie(name, director, actors, intro, duration, score, true);
        movies.add(newMovie);
        System.out.println("影片添加成功！");
    }

    // 修改影片
    private void updateMovie() {
        System.out.println("\n=== 修改影片 ===");
        System.out.print("请输入要修改的影片名称：");
        String name = scanner.nextLine().trim();

        Movie target = null;
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                target = m;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该影片");
            return;
        }

        System.out.print("请输入新片名（不修改请回车）：");
        String newName = scanner.nextLine().trim();
        if (!newName.isEmpty()) {
            // 检查新片名是否已存在
            boolean exists = false;
            for (Movie m : movies) {
                if (m.getName().equals(newName) && !m.getName().equals(name)) {
                    exists = true;
                    break;
                }
            }
            if (exists) {
                System.out.println("错误：新片名已存在");
                return;
            }
            target.setName(newName);
        }

        System.out.print("请输入新导演（不修改请回车）：");
        String director = scanner.nextLine().trim();
        if (!director.isEmpty()) target.setDirector(director);

        System.out.print("请输入新主演（不修改请回车）：");
        String actors = scanner.nextLine().trim();
        if (!actors.isEmpty()) target.setActors(actors);

        System.out.print("请输入新剧情简介（不修改请回车）：");
        String intro = scanner.nextLine().trim();
        if (!intro.isEmpty()) target.setIntro(intro);

        System.out.print("请输入新时长（分钟，不修改请回车）：");
        String durationStr = scanner.nextLine().trim();
        if (!durationStr.isEmpty()) {
            try {
                int duration = Integer.parseInt(durationStr);
                if (duration > 0) target.setDuration(duration);
                else System.out.println("时长输入无效，未修改");
            } catch (NumberFormatException e) {
                System.out.println("时长输入无效，未修改");
            }
        }

        System.out.print("请输入新评分（0-10分，不修改请回车）：");
        String scoreStr = scanner.nextLine().trim();
        if (!scoreStr.isEmpty()) {
            try {
                double score = Double.parseDouble(scoreStr);
                if (score >= 0 && score <= 10) target.setScore(score);
                else System.out.println("评分输入无效，未修改");
            } catch (NumberFormatException e) {
                System.out.println("评分输入无效，未修改");
            }
        }

        System.out.println("影片信息修改完成！");
    }

    // 删除影片
    private void deleteMovie() {
        System.out.println("\n=== 删除影片 ===");
        System.out.print("请输入要删除的影片名称：");
        String name = scanner.nextLine().trim();

        Movie target = null;
        for (Movie m : movies) {
            if (m.getName().equals(name)) {
                target = m;
                break;
            }
        }

        if (target == null) {
            System.out.println("未找到该影片");
            return;
        }

        // 检查是否有排片
        for (Show s : shows) {
            if (s.getMovie().getName().equals(name)) {
                System.out.println("无法删除：该影片已有排片");
                return;
            }
        }

        System.out.print("删除后无法恢复，是否确认删除？(y/n)：");
        String confirm = scanner.nextLine().trim();
        if (confirm.equalsIgnoreCase("y")) {
            movies.remove(target);
            System.out.println("影片删除成功");
        } else {
            System.out.println("已取消删除");
        }
    }

    // 查询影片
    private void queryMovie() {
        System.out.println("\n=== 查询影片 ===");
        System.out.println("1.按片名查询 2.按导演查询 3.按主演查询 4.组合查询");
        System.out.print("请选择查询方式：");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            List<Movie> result = new ArrayList<>();

            switch (choice) {
                case 1:
                    System.out.print("请输入片名：");
                    String name = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getName().contains(name)) result.add(m);
                    }
                    break;

                case 2:
                    System.out.print("请输入导演：");
                    String director = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getDirector().contains(director)) result.add(m);
                    }
                    break;

                case 3:
                    System.out.print("请输入主演：");
                    String actor = scanner.nextLine().trim();
                    for (Movie m : movies) {
                        if (m.getActors().contains(actor)) result.add(m);
                    }
                    break;

                case 4:
                    System.out.print("请输入片名（可为空）：");
                    String n = scanner.nextLine().trim();
                    System.out.print("请输入导演（可为空）：");
                    String d = scanner.nextLine().trim();
                    System.out.print("请输入主演（可为空）：");
                    String a = scanner.nextLine().trim();

                    for (Movie m : movies) {
                        boolean match = true;
                        if (!n.isEmpty() && !m.getName().contains(n)) match = false;
                        if (!d.isEmpty() && !m.getDirector().contains(d)) match = false;
                        if (!a.isEmpty() && !m.getActors().contains(a)) match = false;
                        if (match) result.add(m);
                    }
                    break;

                default:
                    System.out.println("无效选择");
                    return;
            }

            // 显示查询结果
            if (result.isEmpty()) {
                System.out.println("未找到匹配的影片");
            } else {
                System.out.println("查询结果：");
                for (Movie m : result) {
                    m.displayInfo();
                    System.out.println("---------------------");
                }
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 添加场次
    private void addShow() {
        System.out.println("\n=== 添加场次 ===");

        // 显示可选影片
        System.out.println("可选影片：");
        for (int i = 0; i < movies.size(); i++) {
            System.out.printf("%d. %s%n", i + 1, movies.get(i).getName());
        }

        System.out.print("请选择影片（输入序号）：");
        try {
            int movieIndex = Integer.parseInt(scanner.nextLine().trim()) - 1;
            if (movieIndex < 0 || movieIndex >= movies.size()) {
                System.out.println("无效的影片选择");
                return;
            }
            Movie selectedMovie = movies.get(movieIndex);

            System.out.print("请输入放映厅：");
            String hall = scanner.nextLine().trim();
            if (hall.isEmpty()) {
                System.out.println("放映厅不能为空");
                return;
            }

            System.out.print("请输入放映时间（格式：yyyy-MM-dd HH:mm）：");
            String timeStr = scanner.nextLine().trim();
            Date showTime;
            try {
                showTime = sdf.parse(timeStr);
                // 检查时间是否在当前时间之后
                if (showTime.before(new Date())) {
                    System.out.println("放映时间不能早于当前时间");
                    return;
                }
            } catch (ParseException e) {
                System.out.println("时间格式错误");
                return;
            }

            System.out.print("请输入票价：");
            double price;
            try {
                price = Double.parseDouble(scanner.nextLine().trim());
                if (price <= 0) {
                    System.out.println("票价必须大于0");
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("票价格式错误");
                return;
            }

            System.out.print("请输入座位行数：");
            int rowCount;
            try {
                rowCount = Integer.parseInt(scanner.nextLine().trim());
                if (rowCount <= 0) {
                    System.out.println("行数必须大于0");
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("行数格式错误");
                return;
            }

            System.out.print("请输入座位列数：");
            int colCount;
            try {
                colCount = Integer.parseInt(scanner.nextLine().trim());
                if (colCount <= 0) {
                    System.out.println("列数必须大于0");
                    return;
                }
            } catch (NumberFormatException e) {
                System.out.println("列数格式错误");
                return;
            }

            // 创建场次
            Show newShow = new Show(++showIdCounter, selectedMovie, hall, showTime, price, rowCount, colCount);
            shows.add(newShow);
            System.out.println("场次添加成功，场次ID：" + newShow.getId());
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 显示经理菜单
    public void showManagerMenu() {
        while (isLoggedIn()) {
            System.out.println("\n=== 经理操作菜单 ===");
            System.out.println("1. 影片管理");
            System.out.println("2. 场次管理");
            System.out.println("3. 销售统计");
            System.out.println("4. 修改密码");
            System.out.println("5. 退出登录");
            System.out.print("请选择操作：");

            try {
                int choice = Integer.parseInt(scanner.nextLine().trim());
                switch (choice) {
                    case 1:
                        showMovieMenu();
                        break;
                    case 2:
                        showShowMenu();
                        break;
                    case 3:
                        showSalesReport();
                        break;
                    case 4:
                        changePassword();
                        break;
                    case 5:
                        logout();
                        break;
                    default:
                        System.out.println("无效选择（1-5）");
                }
            } catch (NumberFormatException e) {
                System.out.println("请输入数字（1-5）");
            }
        }
    }

    // 影片管理子菜单
    private void showMovieMenu() {
        System.out.println("\n=== 影片管理 ===");
        System.out.println("1. 添加影片 2. 修改影片 3. 删除影片 4. 查询影片 5. 返回上一级");
        System.out.print("请选择：");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            switch (choice) {
                case 1:
                    addMovie();
                    break;
                case 2:
                    updateMovie();
                    break;
                case 3:
                    deleteMovie();
                    break;
                case 4:
                    queryMovie();
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选择（1-5）");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 场次管理子菜单
    private void showShowMenu() {
        System.out.println("\n=== 场次管理 ===");
        System.out.println("1. 添加场次 2. 查看场次 3. 删除场次 4. 返回上一级");
        System.out.print("请选择：");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            switch (choice) {
                case 1:
                    addShow();
                    break;
                case 2:
                    listAllShows();
                    break;
                case 3:
                    deleteShow();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择（1-4）");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 列出所有场次
    private void listAllShows() {
        if (shows.isEmpty()) {
            System.out.println("暂无场次信息");
            return;
        }
        // 按时间排序
        shows.sort(Comparator.comparing(Show::getTime));
        System.out.println("\n=== 所有场次 ===");
        for (Show show : shows) {
            System.out.printf("场次ID：%d，影片：%s，放映厅：%s，时间：%s，票价：%.2f元，座位：%dx%d\n",
                    show.getId(),
                    show.getMovie().getName(),
                    show.getHall(),
                    sdf.format(show.getTime()),
                    show.getPrice(),
                    show.getRowCount(),
                    show.getColCount());
        }
    }

    // 删除场次
    private void deleteShow() {
        System.out.print("请输入要删除的场次ID：");
        try {
            int id = Integer.parseInt(scanner.nextLine().trim());
            Show target = null;
            for (Show show : shows) {
                if (show.getId() == id) {
                    target = show;
                    break;
                }
            }
            if (target == null) {
                System.out.println("未找到该场次");
                return;
            }

            // 检查是否已售票
            for (SaleRecord record : saleRecords) {
                if (record.getShow().getId() == id && !record.isRefunded()) {
                    System.out.println("无法删除：该场次已有售票记录");
                    return;
                }
            }

            // 检查时间是否在当前时间之前
            if (target.getTime().before(new Date())) {
                System.out.println("无法删除：该场次已放映完毕");
                return;
            }

            shows.remove(target);
            System.out.println("场次删除成功");
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 销售统计报表
    private void showSalesReport() {
        System.out.println("\n=== 销售统计 ===");
        System.out.println("1. 按影片统计 2. 按日期统计 3. 返回上一级");
        System.out.print("请选择：");
        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            switch (choice) {
                case 1:
                    statsByMovie();
                    break;
                case 2:
                    statsByDate();
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选择（1-3）");
            }
        } catch (NumberFormatException e) {
            System.out.println("请输入有效数字");
        }
    }

    // 按影片统计
    private void statsByMovie() {
        if (saleRecords.isEmpty()) {
            System.out.println("暂无销售记录");
            return;
        }
        System.out.println("\n=== 按影片销售统计 ===");
        // 统计每个影片的销售额和票数
        // 实现统计逻辑...
        System.out.println("（统计逻辑待实现）");
    }

    // 按日期统计
    private void statsByDate() {
        if (saleRecords.isEmpty()) {
            System.out.println("暂无销售记录");
            return;
        }
        System.out.println("\n=== 按日期销售统计 ===");
        // 实现按日期统计逻辑...
        System.out.println("（统计逻辑待实现）");
    }

    // 修改密码
    private void changePassword() {
        if (!isLoggedIn()) {
            System.out.println("请先登录");
            return;
        }

        System.out.print("请输入旧密码：");
        String oldPwd = scanner.nextLine().trim();
        String encryptedOld = MD5Util.encrypt(oldPwd);

        if (!encryptedOld.equals(currentManager.getPassword())) {
            System.out.println("旧密码错误");
            return;
        }

        System.out.print("请输入新密码（至少6位）：");
        String newPwd = scanner.nextLine().trim();
        if (newPwd.length() < 6) {
            System.out.println("密码长度不能少于6位");
            return;
        }

        System.out.print("请确认新密码：");
        String confirmPwd = scanner.nextLine().trim();
        if (!newPwd.equals(confirmPwd)) {
            System.out.println("两次输入不一致");
            return;
        }

        currentManager.setPassword(MD5Util.encrypt(newPwd));
        currentManager.setNeedChangePassword(false);
        System.out.println("密码修改成功");
    }

    // 添加销售记录（供前台调用）
    public void addSaleRecord(SaleRecord record) {
        saleRecords.add(record);
    }

    // getter方法
    public List<Movie> getMovies() {
        return new ArrayList<>(movies); // 返回副本防止外部修改
    }

    public Show[] getShows() {
        return shows.toArray(new Show[0]);
    }

    public List<SaleRecord> getSaleRecords() {
        return new ArrayList<>(saleRecords);
    }

    // 查找场次
    public Show findShowById(int id) {
        for (Show show : shows) {
            if (show.getId() == id) {
                return show;
            }
        }
        return null;
    }

    // 登录状态管理
    public void setCurrentManager(User manager) {
        this.currentManager = manager;
    }

    public boolean isLoggedIn() {
        return currentManager != null;
    }

    public void logout() {
        currentManager = null;
        System.out.println("已退出登录");
    }
}